<template>
  <van-button
    :icon="value ? 'star' : 'star-o'"
    :loading="isloadingState"
    :class="{
      collected: value
    }"
    @click="switchCollectionStatus"
  />
</template>

<script>
// 导入收藏及取消收藏文章的接口请求
import { collectArticles, cancelCollectArticles } from '@/api/users'
export default {
  name: 'CollectionArticle',
  props: {
    // 接收父组件传递服务器是否已收藏布尔值
    value: {
      type: Boolean,
      required: true
    },
    // 接收父组件传递当前文章ID
    carticleID: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      // 收藏加载状态
      isloadingState: false
    }
  },
  methods: {
    // 收藏或者取消文章收藏
    async switchCollectionStatus () {
      // 开启加载状态
      this.isloadingState = true
      try {
        if (this.value) {
          // 当服务器收藏状态为True，点击则取消收藏
          await cancelCollectArticles(this.carticleID)
          this.$toast.success('取消文章收藏！')
        } else {
          // 否则为收藏该文章
          await collectArticles(this.carticleID)
          this.$toast.success('文章收藏成功！')
        }
        this.$emit('input', !this.value)
      } catch (err) {}
    }
  }
}
</script>

<style scoped lang="less">
.collected {
  /deep/.van-icon {
    color: #ffa500;
  }
}

</style>
